package projectexp

import (
	"context"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
	"wh-1-backend/internal/dao"
	"wh-1-backend/internal/model"
	"wh-1-backend/internal/model/do"
	"wh-1-backend/internal/model/entity"
	"wh-1-backend/internal/service"
)

type sProjectExp struct{}

func New() *sProjectExp {
	return &sProjectExp{}
}

func init() {
	service.RegisterProjectExp(New())
}

func (p *sProjectExp) Insert(ctx context.Context, list []*model.EditProjectExperienceInput) (err error) {
	data := make([]*do.ProjectExperience, 0, 8)
	for _, input := range list {
		data = append(data, &do.ProjectExperience{
			ResumeId: input.ResumeId,
			From:     input.From,
			End:      input.End,
			Title:    input.Title,
			Content:  input.Content,
		})
	}
	_, err = dao.ProjectExperience.Ctx(ctx).Insert(data)
	return
}

func (p *sProjectExp) GetByResumeId(ctx context.Context, resumeId uint) (res []*entity.ProjectExperience, err error) {
	res = []*entity.ProjectExperience{}
	err = dao.ProjectExperience.Ctx(ctx).Where(dao.ProjectExperience.Columns().ResumeId, resumeId).Scan(&res)
	return
}

func (p *sProjectExp) UpdateByResumeId(ctx context.Context, resumeId uint, list []*model.EditProjectExperienceInput) (err error) {
	err = g.DB().Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
		_, err2 := dao.ProjectExperience.Ctx(ctx).Where(dao.ProjectExperience.Columns().ResumeId, resumeId).Delete()
		if err2 != nil {
			return err2
		}
		if list == nil || len(list) == 0 {
			return nil
		} else {
			err2 = p.Insert(ctx, list)
		}
		return err2
	})
	return err
}
